package com.xyrl.third.aliyun.service;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.xyrl.common.util.ObjectUtil;
import com.xyrl.third.aliyun.config.AliYunProperties;
import com.xyrl.third.aliyun.exception.AliYunException;
import com.xyrl.third.aliyun.vo.AliYunResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.Map;

/**
 * 阿里云语音工具类
 *
 * @author zhongp
 * @version 1.0
 * @className SingleCallService
 * @company 星纭融链科技服务有限公司
 * @date 2020-01-02 16:50:18
 * @Description
 */
@Slf4j
public class SingleCallService {

    @Autowired
    private AliYunProperties aliYunProperties;

    /**
     * 发送语音验证码
     *
     * @param sendSigleMap 语音验证码数据
     * @return
     * @description https://help.aliyun.com/document_detail/114035.html?spm=a2c4g.11174283.6.561.489e700aXlgaDQ
     */
    public AliYunResponse sendSingle(Map<String, String> sendSigleMap) {
        DefaultProfile profile = DefaultProfile.getProfile(aliYunProperties.getRegionId(), aliYunProperties.getAccessKeyId(), aliYunProperties.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dyvmsapi.aliyuncs.com");
        //当天日期  发送版本
        request.setSysVersion(DateUtil.format(new Date(), DatePattern.NORM_DATE_PATTERN));
        request.setSysAction("SingleCallByTts");
        //默认
        request.putQueryParameter("RegionId", aliYunProperties.getRegionId());
        for (String key : sendSigleMap.keySet()) {
            request.putQueryParameter(key, sendSigleMap.get(key));
        }
        try {
            CommonResponse response = client.getCommonResponse(request);
            log.info("发送语音验证码返回值:[{}]", response.getData());
            if (ObjectUtil.isNotEmpty(response.getData())) {
                AliYunResponse aliYunResponse = JSONObject.parseObject(response.getData(), AliYunResponse.class);
                return aliYunResponse;
            }
            throw new AliYunException("短信发送异常");
        } catch (ServerException e) {
            log.error("发送语音验证码失败", e);
            throw new AliYunException(e.getMessage());
        } catch (ClientException e) {
            log.error("发送语音验证码失败", e);
            throw new AliYunException(e.getMessage());
        }
    }
}
